﻿
''' <summary>
''' 工程邮件配置界面
''' </summary>
''' <remarks></remarks>
Public Class CarMailCfg

    Private projectId As String
    Private carProjectName As String
    Private bsaved As Boolean = False

    Public Sub New(ByVal projectId As String, ByVal carProjectName As String)

        ' 此调用是 Windows 窗体设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。
        Me.projectId = projectId
        Me.carProjectName = carProjectName
    End Sub


    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
        SetEditStatus(False)

    End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        If (Not IsValidate()) Then
            Return
        End If
        SetEditStatus(True)
        ''========================
        '' saving
        save()
        bsaved = True
        ''=======================
        '' Craete Directory
        Dim dir = Application.StartupPath + "\Mails\" + carProjectName
        If (Not System.IO.Directory.Exists(dir)) Then
            Try
                System.IO.Directory.CreateDirectory(dir)
            Catch ex As Exception
                MessageBox.Show("创建邮件缓存目录失败", "系统提示", MessageBoxButtons.OK)
            End Try

        End If
        If (bsaved) Then Me.txtPassword.PasswordChar = "*"
        MessageBox.Show("保存成功")
    End Sub

    ''' <summary>
    ''' 更新编辑状态
    ''' </summary>
    ''' <param name="bstate">是否处于编辑状态</param>
    ''' <remarks></remarks>
    Private Sub SetEditStatus(ByVal bstate)
        btnEdit.Enabled = bstate
        btnSave.Enabled = Not bstate

        Me.txtSubject.ReadOnly = bstate
        Me.txtBody.ReadOnly = bstate

        Me.txtMailTo.ReadOnly = bstate

        Me.txtFrom.ReadOnly = bstate
        Me.txtPassword.ReadOnly = bstate
        Me.txtSmtp.ReadOnly = bstate
    End Sub

    Private Sub CarMailCfg_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        SetEditStatus(True)
        LoadData(projectId)
    End Sub

    ''' <summary>
    ''' 加载数据
    ''' </summary>
    ''' <param name="projectId">项目编号</param>
    ''' <remarks></remarks>
    Private Sub LoadData(ByVal projectId As String)
        Dim mailfrom As MailFrom
        mailfrom = CarMailService.GetMailFrom(projectId)

        If (mailfrom IsNot Nothing) Then
            '' 显示mail from
            Me.txtFrom.Text = mailfrom.Account
            Me.txtPassword.Text = mailfrom.Password

            If txtPassword.Text.Length > 0 Then txtPassword.PasswordChar = "*"

            Me.txtSmtp.Text = mailfrom.SMTP

            Me.txtSubject.Text = mailfrom.Subject
            Me.txtBody.Text = mailfrom.Body
        End If

        Dim lst As List(Of MailTo)
        lst = CarMailService.GetMailTo(projectId)
        If (lst.Count > 0) Then
            Dim str As String = ""
            For Each mt As MailTo In lst
                str &= mt.TO + ";"
            Next
            str = str.Remove(str.Length - 1, 1)
            Me.txtMailTo.Text = str
        End If

        '  mailitem = New MailItem()
        '  mailitem.From = mailfrom
        '  mailitem.ProjectId = projectId
        '  mailitem.TO = lst
    End Sub

    ''' <summary>
    ''' 检测是否通过验证
    ''' </summary>
    ''' <returns>如果是则返回true</returns>
    ''' <remarks></remarks>
    Private Function IsValidate() As Boolean
        Dim bReturn As Boolean = True

        If Not IsItemValidate(Me.txtFrom, "发件人地址不能为空") Then
            Return False
        End If
        If (Not IsEmail(txtFrom.Text.Trim())) Then
            MessageBox.Show("发件人地址格式不正确", "系统提示!", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Me.txtFrom.Focus()
            Return False
        End If
        If Not IsItemValidate(Me.txtPassword, "邮箱密码不能为空") Then
            Return False
        End If
        If Not IsItemValidate(Me.txtSmtp, "发送邮件服务器(SMTP)不能为空") Then
            Return False
        End If
        If Not IsItemValidate(Me.txtMailTo, "收件人地址不能为空") Then
            Return False
        End If
        If Not IsItemValidate(Me.txtSubject, "邮件标题不能为空") Then
            Return False
        End If
        If Not IsItemValidate(Me.txtBody, "邮件正文不能为空") Then
            Return False
        End If
        ''===================================
        '' 发件人数量
        Dim str As String = Me.txtMailTo.Text.Trim()
        If str.EndsWith(";") Then
            str = str.Remove(str.Length - 1)
        End If

        Dim sts() As String = str.Split(";")
        For Each st As String In sts
            st = st.Trim()
            If (String.IsNullOrEmpty(st)) Then
                Continue For
            End If
            If (Not IsEmail(st)) Then
                MessageBox.Show("收件人地址格式不正确", "系统提示!", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Me.txtMailTo.Focus()
                Return False
            End If
        Next

        If (sts.Length > 5) Then
            MessageBox.Show("收件人地址不能为空", "系统提示!", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Me.txtMailTo.Focus()
            Return False
        End If

        Return bReturn
    End Function

    ''' <summary>
    ''' 验证是否是电子邮件
    ''' </summary>  
    Private Function IsEmail(ByVal str As String) As Boolean
        Return System.Text.RegularExpressions.Regex.IsMatch(str, "^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$")
    End Function

    ''' <summary>
    ''' 验证具体的某个文本框内容是否为空
    ''' </summary>
    Private Function IsItemValidate(ByVal txt As TextBox, ByVal msg As String) As Boolean
        If txt.Text.Trim().Length = 0 Then
            MessageBox.Show(msg, "系统提示!", MessageBoxButtons.OK, MessageBoxIcon.Information)
            txt.Focus()
            Return False
        End If
        Return True
    End Function

    ''' <summary>
    ''' 保存配置
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub save()
        Dim mailfrom As New MailFrom

        '' ====================================
        '' MailFrom
        mailfrom.ProjectId = projectId
        mailfrom.Account = Me.txtFrom.Text
        mailfrom.Password = Me.txtPassword.Text
        mailfrom.SMTP = Me.txtSmtp.Text

        mailfrom.Subject = Me.txtSubject.Text
        mailfrom.Body = Me.txtBody.Text
        CarMailService.SaveMailFrom(mailfrom)
        ''=====================================
        '' MailTO
        Dim str As String = Me.txtMailTo.Text.Trim()
        If str.EndsWith(";") Then
            str = str.Remove(str.Length - 1)
        End If
        Dim sts() As String = str.Split(";")

        CarMailService.RemoveMailTo(projectId)
        Dim mailto As New MailTo
        mailto.ProjectId = projectId
        For Each st As String In sts
            st = st.Trim()
            If (String.IsNullOrEmpty(st)) Then
                Continue For
            End If
            mailto.TO = st
            CarMailService.SaveMailTo(mailto)
        Next
    End Sub

    Private Sub txtPassword_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPassword.TextChanged
        If txtPassword.Text.Length = 0 Then txtPassword.PasswordChar = ""
    End Sub

    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        SetEditStatus(True)
        CarMailService.RemoveMailTo(projectId)
        CarMailService.RemoveMailFrom(projectId)
        ''===================
        Me.txtPassword.Clear()
        Me.txtMailTo.Clear()
        Me.txtBody.Clear()
        Me.txtFrom.Clear()
        Me.txtSmtp.Clear()
        Me.txtSubject.Clear()

        MessageBox.Show("删除成功")
    End Sub
End Class